package io.kumao.gateway.service;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 * Java对象和Json对象转换服务.
 *
 * @author 崔作利
 */
@Slf4j
@Service
public class OjmService {

    private final ObjectMapper objectMapper = new ObjectMapper();

    /**
     * object
     *
     * @param content
     * @param valueType
     * @param <T>
     * @return
     */
    public <T> T object(String content, Class<T> valueType) {
        try {
            return objectMapper.readValue(content, valueType);
        } catch (IOException e) {
            log.error("OJM object error - {}, {}", ExceptionUtils.getStackTrace(e), content);
        }
        return null;
    }

    /**
     * object
     *
     * @param content
     * @param typeReference
     * @param <T>
     * @return
     */
    public <T> T object(String content, TypeReference<T> typeReference) {
        try {
            return objectMapper.readValue(content, typeReference);
        } catch (IOException e) {
            log.error("OJM object error - {}, {}", ExceptionUtils.getStackTrace(e), content);
        }
        return null;
    }

    /**
     * json
     *
     * @param object
     * @return
     */
    public String json(Object object) {
        try {
            return objectMapper.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            log.error("OJM json error - {}, {}", ExceptionUtils.getStackTrace(e), object);
        }
        return null;
    }
}
